import { reqGetCode, reqRegister, reqUserLogin, reqUserInfo, reqUserLogout } from '@/api';

//登录、注册模块的小仓库
let state = {
     // 验证码
     code: '',
     // 身份标识符
     token: localStorage.getItem('TOKEN'),
     // 用户名
     nickName: ''

};
let mutations = {
     GETCODE(state, code) {
          state.code = code
     },
     SET_TOKEN(state, token) {
          state.token = token
     },

     SET_USERINFO(state, nickName) {
          state.nickName = nickName
     },
     CLEAR(state){
          // 清除相关信息
          state.token = '';
          state.nickName = '';
          localStorage.removeItem('TOKEN')

     }
};
let actions = {
     // 获取验证码
     async getCode({ commit, dispatch, state }, phone) {
          let result = await reqGetCode(phone)
          if (result.code == 200) {
               commit('GETCODE', result.data)
               return 'ok'
          } else {
               return Promise.reject()
          }

     },

     // 注册
     async registerUser({ commit, dispatch, state }, obj) {
          let result = await reqRegister(obj)
          if (result.code == 200) {
               return 'ok'
          } else {
               return Promise.reject(new Error(result.message))
          }
     },

     // 用户登录
     async userLogin({ commit, dispatch, state }, data) {
          let result = await reqUserLogin(data)
          if (result.code == 200) {
               commit('SET_TOKEN', result.data.token)

               // 持久化存储
               localStorage.setItem('TOKEN', result.data.token)

               return 'ok'
          } else {
               return Promise.reject(new Error(result.message))
          }

     },

     // 获取用户信息
     async getUserInfo({ commit, dispatch, state }) {
          let result = await reqUserInfo()
          if (result.code == 200) {
               commit('SET_USERINFO', result.data.nickName)
               return 'ok'
          } else {
               return Promise.reject()
          }
     },

     // 退出登录
     async logout({ commit, dispatch, state }) {
          let result = await reqUserLogout()
          if (result.code == 200) {
               commit('CLEAR')
               return 'ok'
          } else {
               return Promise.reject(new Error(result.message))
          }
     }


};
let getters = {};

//对外暴露
export default {
     state,
     mutations,
     actions,
     getters
}